package com.ashlikun.core.mvvm

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner

/**
 * 作者　　: 李坤
 * 创建时间: 2020/3/31　17:44
 * 邮箱　　：496546144@qq.com
 *
 * 功能介绍：自己实现ViewModelProvider
 */
open class XViewModelProvider(val store: ViewModelStore, var factory: Factory) :
    ViewModelProvider(store, factory) {

    constructor(owner: ViewModelStoreOwner, factory: Factory) : this(owner.viewModelStore, factory)


    override fun <T : ViewModel> get(key: String, modelClass: Class<T>): T {
        val model = super.get(key, modelClass)
        //是否重新创建
        if (factory is ViewModelFactoryImp) {
            (factory as ViewModelFactoryImp).isReCreate(model)
        }
        return model
    }

    override  fun <T : ViewModel> get(modelClass: Class<T>): T {
        val model = super.get(modelClass)
        //是否重新创建
        if (factory is ViewModelFactoryImp) {
            (factory as ViewModelFactoryImp).isReCreate(model)
        }
        return model
    }


    fun <T : ViewModel> forEach(block: (vm: T) -> Unit) {
        store.keys().forEach {
            block.invoke(store.get(it) as T)
        }
    }
}